/**
 * @desc:  增加设备升级、编辑、查看
 * @author qiankui
 * @date 2023-4-19 14:11:31
*/
<template>
    <el-dialog :close-on-click-modal="false" :visible="addViewEditFlag" class="zdy-dialog" width="800px"
               :title="title" :before-close="handleCloseDialog">
      <el-form :model="form" class="pop-form-box" :rules="rules" ref="ruleForm">

        <el-row :gutter="20">
          <el-col :span="12">
            <!--设备类型-->
            <el-form-item :label="$t('Device type')" prop="deviceType">
              <!--<el-input v-if="dialogType=='view'" :disabled="true" :title="form.deviceNames" v-model="form.deviceNames"></el-input>-->
              <!--请选择设备类型-->
              <el-select @change="devTypeChange" :disabled="dialogType!='add'" v-model="form.deviceType" :placeholder="$t('Please select the device type')">
                <el-option :label="$t(item.label)" :value="item.value" v-for="(item,index) in devOptions" :key="item.label" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!--接收设备-->
            <el-form-item :label="$t('receiver')" prop="deviceCodes">
              <el-input style="width: 100%" v-if="dialogType!='add'" :disabled="true" :title="form.deviceNames" v-model="form.deviceNames"></el-input>
              <!--请选择接收设备-->
              <el-select @change="deviceCodesChange" v-if="dialogType=='add'" multiple collapse-tags v-model="form.deviceCodes" :placeholder="$t('Please select the receiving device')">
                <el-option :label="item.deviceName" :value="item.deviceCode" v-for="(item,index) in devList" :key="item.id" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!--升级类型-->
            <el-form-item :label="$t('Upgrade type')" prop="upgradeType">
              <!--请选择升级类型-->
              <el-select :disabled="dialogType!='add'" v-model="form.upgradeType" :placeholder="$t('Select an upgrade type')">
                <el-option :label="$t(item.label)" :value="item.value" v-for="(item,index) in updateType" :key="item.label" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--版本号-->
            <el-form-item :label="$t('Version number')" prop="version">
              <el-input :disabled="dialogType!='add'" v-model="form.version" :minlength="$rules.version.min"
                        :maxlength="$rules.version.max"
                        show-word-limit>
                <template v-if="dialogType=='add'" slot="prepend">V</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!--描述-->
            <el-form-item :label="$t('Description')" prop="description">
              <el-input
                  :disabled="dialogType=='view'"
                  type="textarea"
                  :rows="4"
                  :placeholder="$t('Please enter content')"
                  v-model="form.description">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24" v-if="dialogType=='add'">
            <span>{{form.fileName}}</span>
            <!--更新包-->
            <el-form-item :label="$t('Update package')" prop="filePath">
              <el-upload  ref="upload" class="upload-demo" action="#"
                          :accept="updateFileAccept"
                          :auto-upload="false"
                          :on-change="(event)=>{onchange(event)}"
                          :before-remove="removeFile" :limit="2">
                <!--上传更新包-->
                <el-button size="mini" class="dia-sc-btn"> <span class="iconfont-KUI icon-fujian"></span>{{this.i18n.t('Upload update package')}}</el-button>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="dialogType!='add'">
            <!--更新包-->
            <el-form-item :label="$t('Update package')">
              <el-input :disabled="true" :title="form.fileName" v-model="form.fileName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
        <div class="footBtnBox">
            <el-button size="small" type="handle" @click="handleCloseDialog">{{this.i18n.t('Cancel')}}</el-button>
            <el-button size="small" type="primary" :loading="saveloading" v-if="dialogType!='view'" @click="submitForm">{{this.i18n.t('save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {deviceTypeList,deviceUpdateType} from '@/assets/common/js/utils/deviceConfig.js'
    import {deviceinfoGetallonlinedevices,deviceversionCreate,deviceversionUpdatadescription,deviceinfoGetallonlinedevicesbydevicetype} from "@/api/pcmj/sbsj";
import { uploadfile, uploadfileinfodata } from '@/api/globaTableData' //引入接口
import { otaUpdate, otaCreate, otaGet, } from '@/api/otagl'//引入接口
import { create } from '@/api/document'//引入接口
export default {
    name: "addUpgrade",
    components: {},
    props: {
        addViewEditFlag: {
            type: Boolean,
            default: false
        },
        dialogType:{
            type: String,
            defautl: () => {
                return 'add'
            }
        },
        editTableRow: {
            type: Object,
            defautl: () => {
                return {}
            }
        }
    },
    watch: {

    },
    data() {
        var validateVersion= (rule, value, callback) => {
            value=value||""
            console.log(value);
            if (value == '') {
                // 请输入版本号
                callback(new Error(this.i18n.t('Please enter the version number')));
            }else if (!this.$rules.version.reg.test(value)) {
                // 英文、数字
                callback(new Error(this.i18n.t('English、digital, length is xxx ~ xxx characters！') + this.$rules.version.min + '~' + this.$rules.version.max + this.i18n.t('bits')));
            }else {
                callback();
            }
        };
        var validateDescription = (rule, value, callback) => {
            // debugger
            var descriptionReg=/^[\s\S]{1,500}$/
            console.log(133,value);
            // if (value === '') {
                // 请输入描述
                // callback(new Error(this.i18n.t('Please enter a description')));
            // }else
            if (value.length > 0) {
                if (!descriptionReg.test(value)) {
                    // 描述长度1~500位!
                    callback(new Error(this.i18n.t('Description Length 1 to 500 characters!')));
                }else {
                    callback();
                }
            }else {
                callback();
            }
        };
        return {
            devList:[],
            devOptions:[],
            updateType:[],
            saveDisabled:true,
            saveloading:false,
            loadingTips:false,
            errTips:false,
            percentage:0,
            sbjxArr:null,
            sbxhArr:null,
            updateFileAccept:".img,.zip,.bin",
            form:{
                version:'',
                description:'',
                deviceType:0,
                filePath:"",
                upgradeType:0,
                deviceCodes:null
            },
            title: '',
            otaglForm: {
                name: '',
                version: "",
                devieModel: '',
                description: "",

            },
            syjxVal: [],
            fileName: '',
            rules: {
                description: [
                    { validator: validateDescription,required: false, trigger: 'blur' }
                ],
                version:[
                    { validator: validateVersion,required: true, trigger: 'blur' }
                ],
                deviceCodes:[
                    // 请选择接收设备
                    { required: true, trigger: 'blur',message:this.i18n.t('Please select the receiving device') }
                ],
                deviceType:[
                    // 请选择设备类型
                    { required: true, trigger: 'blur',message:this.i18n.t('Please select the device type')  }
                ],
                upgradeType:[
                    // 请选择升级类型
                    { required: true, trigger: 'blur',message:this.i18n.t('Select an upgrade type')  }
                ],
                filePath:[
                    // 请选择更新包
                    { required: true, trigger: 'blur',message:this.i18n.t('Please select an update package')  }
                ],
            }
        }
    },
    mounted() {
        var typeList={
            // 新增
            'add':this.i18n.t('add'),
            // 查看
            'view':this.i18n.t('view'),
            // 编辑
            'edit':this.i18n.t('edit'),
        }
        if(this.dialogType=='view'||this.dialogType=='edit'){
            this.form=JSON.parse(JSON.stringify(this.editTableRow))
            this.rules.deviceCodes[0].required=false
            console.log(202,this.editTableRow);
            // if(){
            //
            // }
            this.$set(this.form,'deviceCodes',[])
        }

        this.title=typeList[this.dialogType]
        this.devOptions=deviceTypeList.slice(0,3)
        this.updateType=deviceUpdateType
        // this.deviceinfoGetallonlinedevices()
        this.devTypeChange(this.form.deviceType)
        console.log(174,this.dialogType,this.form);
        this.$nextTick(() => {
            this.$refs['ruleForm'].resetFields();
        })

    },
    methods: {
      deviceCodesChange(item){
        console.log(item);
        if (item.length){
          this.$refs.ruleForm.clearValidate(['deviceCodes']);
        }
      },
        devTypeChange(val){
            console.log(val);
            this.form.deviceCodes=null
            deviceinfoGetallonlinedevicesbydevicetype(val).then((res) => {
                if (res.code === 200) {
                    this.devList=res.data
                }
            }).catch(err=>{

            }).finally(() => {

            })
        },
        // 更新父页面的数据
        updateParentData(){
            this.$emit("update:addViewEditFlag",false);
            this.$parent.onSearch()
        },
        // 更新升级包描述
        deviceversionUpdatadescription(params){
            deviceversionUpdatadescription(params).then((res) => {
                if (res.code === 200) {
                    // 修改成功
                    this.W.$tips("success", this.i18n.t('Modified successfully!'));
                    // 更新父页面的数据
                    this.updateParentData()
                }
            }).catch(err=>{

            }).finally(() => {
                this.saveloading=false
            })
        },
        // 添加升级包
        deviceversionCreate(params){
            deviceversionCreate(params).then((res) => {
                if (res.code === 200) {
                    // 添加成功
                    this.W.$tips("success", this.i18n.t('Add successfully!'));
                    // 更新父页面的数据
                    this.updateParentData()
                }
            }).catch(err=>{

            }).finally(() => {
                this.saveloading=false
            })
        },
        deviceinfoGetallonlinedevices(){
            deviceinfoGetallonlinedevices().then((res) => {
                if (res.code === 200) {
                    // debugger
                    if(res.data.length){
                        this.devList=res.data
                        this.$nextTick(() => {
                            console.log(205,this.form.deviceCodes,this.form);

                        })

                    }else{
                        this.devList=[]
                    }

                }
            }).catch(err=>{

            }).finally(() => {

            })
        },
        onchange(file){
            this.$refs.ruleForm.clearValidate(['filePath'])
            console.log(file);
            var fileList=this.$refs.upload.$refs["upload-inner"].fileList
            console.log(fileList);

            if (fileList.length > 1) {
                fileList.splice(0, 1)
            }

            var suffix=this.getSuffix(file.name)
            console.log(396,suffix);
            if(this.updateFileAccept.indexOf(suffix)==-1){
                // 请选择后缀是img或zip的文件
                this.W.$tips("warning", this.i18n.t('please select a file with an img or zip suffix!'));
              this.$refs.upload.clearFiles()
                return
            }
            if (!this.isElectron){
                // 请在桌面端操作
                this.W.$tips("warning", this.i18n.t('Please operate on the desktop!'));
              this.$refs.upload.clearFiles()
            }else{
                this.form.filePath=file.raw.path
                console.log('文件路径',file.raw.path);
            }
            console.log(file);
        },
        removeFile(){
            this.$refs.upload.$refs["upload-inner"].fileList.length=0
            this.form.filePath=""
        },
        sbxhChange(){

        },
        /**
         * @description  关闭弹窗事件
         * @return not
         * @author xiongyi 2022-06-29 16:48:08
         **/
        handleCloseDialog() {
            // 新增
            this.title = this.i18n.t('add');
            this.$emit('update:addViewEditFlag', false);
            this.$emit('update:editTableRow', null);
            if (this.fileName) {
                this.$refs.upload.clearFiles()
            }

        },
        /**
        * @description  保存
        * @param  not
        * @return not
        * @author xiongyi 2022-07-06 10:50:18
        **/
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                console.log(275,this.form);
                if (valid) {
                    this.saveloading=true
                    const sendData = JSON.parse(JSON.stringify(this.form));
                    if(this.dialogType=='view'){
                        sendData.version = 'V'+sendData.version;
                    }
                    console.log(sendData);
                    if(this.dialogType=='add'){
                        this.deviceversionCreate(sendData)
                    }else if(this.dialogType=='edit'){
                        this.deviceversionUpdatadescription(sendData)
                    }
                }
            })
        },
        // 提取文件后缀名
        getSuffix(str) {
            const fileExtension = str.substring(str.lastIndexOf('.') + 1);
            return fileExtension;
        }
    }
}
</script>

<style scoped lang="scss">
    .el-dialog-div {
        height:470px;
        overflow-x: hidden;
    }
.zh-tip {
    position: relative;
    color: #727b8f;
    text-align: right;
    .tb-btn {
        color: #4264d0;
        text-decoration: underline;
        cursor: pointer;
    }
}
//.dia-sc-btn {
//    background-color: transparent;
//    border: 1px dashed rgba(55, 101, 215, 0.5);
//    color: rgba(55, 101, 215, 0.5);
//}
</style>
